const App = getApp()
const db = wx.cloud.database()
const _ = db.command
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    // 提交按钮加载
    btnLoading: false,
    // 默认头像
    fileList: [],
    applist: [{
      name: '文件',
      icon: "icon-wenjian",
      color: "repeating-linear-gradient(45deg, #209CFF, #68E0CF);",
      path: "/pages/myclass/details/folder/index",
      bind: "appFolder",
    }, ],
    // 班级数据
    myclass: [],
    // 用户在群里的信息
    classInfo: "",
    // 更新后的数据
    setclasss: {
      setfileList: "",
      calssName: "",
      infoName: "",
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this
    let myclassId = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值后', myclassId);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      myclassId: myclassId
    })
    that.getmyclass()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    that.getmyclass()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 弹窗
  showPopup() {
    this.setData({
      show: true
    });
  },
  // 关闭弹窗
  onClose() {
    this.setData({
      show: false
    });
  },
  // 头像
  afterRead(event) {
    const {
      file
    } = event.detail;
    console.log('获取到的临时头像', file);
    that.setData({
      btnLoading: true,
      'fileList[0]': file
    })
    let cloudPath = "calssAvatar/" + new Date().getTime() + ".png"
    wx.cloud.uploadFile({
      cloudPath: cloudPath, // 上传至云端的路径
      filePath: file.thumb, // 小程序临时文件路径
      success: res => {
        // 返回文件 ID
        console.log('返回来的照片id', res.fileID)
        that.setData({
          ['setclasss.setfileList']: res.fileID,
          btnLoading: false,
        })
      },
      fail: function (res) {
        console.log(res);
        that.setData({
          btnLoading: false,
        })
      }
    })

  },
  // 删除头像
  deleteImg(event) {
    const delIndex = event.detail.index
    const {
      fileList
    } = this.data
    fileList.splice(delIndex, 1)
    this.setData({
      fileList: fileList
    })
  },
  // 获取input输入的值
  handleChange(e, key) {
    const {
      detail,
      currentTarget
    } = e
    this.setData({
      [`setclasss.${currentTarget.id}`]: detail.value,
    })
  },
  // 根据班级id获取班级详情
  getmyclass() {
    console.log('班级详情的id', that.data.myclassId);
    db.collection('myclass').where({
        myclassId: that.data.myclassId
      })
      .get({
        success: function (res) {
          console.log('获取班级详情', res.data[0])
          let classArr = res.data[0]
          // 筛选出本人的信息
          let UserInfo = that.data.UserInfo
          let classInfo = classArr.list.filter(n => n.account == UserInfo.account)
          let Fivelist = classArr.list.slice(0, 5)
          console.log('Fivelist', Fivelist);
          that.setData({
            myclass: classArr,
            Fivelist: Fivelist,
            classInfo: classInfo[0],
            fileList: [{
              thumb: classArr.calssAvatar,
              type: "image",
              url: classArr.calssAvatar
            }],
            'setclasss.calssName': classArr.name,
            'setclasss.setfileList': classArr.calssAvatar,
            'setclasss.infoName': classInfo[0].nickName,
          })
        }
      })
  },
  // 更新
  setmyclass() {
    let setlist = that.data.setclasss
    let myclass = that.data.myclass
    console.log('setlist', setlist);
    App.toast.showLoading('更新中')
    if (that.data.UserInfo.account === myclass.Administrator) {
      console.log('我是创始人');
      // 创始人可以更新群信息和个人名称
      db.collection('myclass').where(_.and([{
          myclassId: myclass.myclassId
        },
        {
          list: {
            account: _.eq(that.data.UserInfo.account)
          }
        }
      ])).update({
        data: {
          name: setlist.calssName,
          calssAvatar: setlist.setfileList,
          'list.$.nickName': setlist.infoName
        },
        success: function (res) {
          console.log(res);
          App.toast.hideLoading()
          App.toast.showToast('更新成功', 'none')
          console.log('更新我的群名称成功')
          let Chat = {
            name: setlist.calssName,
            id: myclass.myclassId,
            Avatar: setlist.setfileList,
          }
          that.setChat(Chat)
          that.onClose()
          that.getmyclass()

        }
      })
    } else if (that.data.UserInfo.permissions === true) {
      // 管理员更新群信息
      db.collection('myclass').where(_.or([{
          myclassId: myclass.myclassId
        },
        {
          permissions: _.eq(that.data.UserInfo.permissions)
        }
      ])).update({
        data: {
          name: setlist.calssName,
          calssAvatar: setlist.setfileList,
        },
        success: function (res) {
          App.toast.hideLoading()
          App.toast.showToast('更新成功', 'none')
          console.log('更新我的群名称成功')
          let Chat = {
            name: setlist.calssName,
            id: myclass.myclassId,
            Avatar: setlist.setfileList,
          }
          that.setChat(Chat)
          that.onClose()
          that.getmyclass()
        }
      })
    } else {
      // 不是管理员不是创建人只能更新自己的群名称
      db.collection('myclass').where(_.and([{
          myclassId: myclass.myclassId
        },
        {
          list: {
            account: _.eq(that.data.UserInfo.account)
          }
        }
      ])).update({
        data: {
          'list.$.nickName': setlist.infoName
        },
        success: function (res) {
          App.toast.hideLoading()
          App.toast.showToast('更新成功', 'none')
          console.log('更新我的群名称成功')
          that.onClose()
          that.getmyclass()
        }
      })
    }


  },
  // 更新讨论区名字
  setChat(e) {
    db.collection('chat-msg').where({
        ChatCommunityId: 'chat' + e.id
      }).update({
        data: {
          ChatCommunityName: e.name,
          className: e.name,
          calssAvatar: e.Avatar
        }
      })
      .then(res => {
        console.log(res);
      })
  },

  // 复制班级号
  CopyMyclassId(e) {
    console.log(e);
    let myclassId = String(e.currentTarget.dataset.myclassid)
    console.log(myclassId);
    wx.setClipboardData({
      data: myclassId,
      success: res => {
        App.toast.showToast('班级号已复制', 'none', 1000)
      }
    })
  },

  // 解散班级
  removeMyclass(e) {
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要在此和同学们告别吗？',
      success(res) {
        if (res.confirm) {
          console.log('拿到当前id了吗', id);
          db.collection('myclass').doc(id).remove({
            success: function (res) {
              console.log(res)
              // 同时解散聊天社区
              let chatId = 'chat' + that.data.myclass.myclassId
              db.collection('chat-msg').where({
                ChatCommunityId: chatId
              }).remove({
                success: function (res) {
                  console.log('已解散', res);
                  App.toast.showToast(that.data.myclass.name + '已解散', 'none')
                  App.route.redirTo('/pages/myclass/list/index')
                }
              })
            }
          })

        } else if (res.cancel) {
          App.toast.showToast('吓死我啦', 'error')
        }
      }
    })
  },
  // 退出班级
  launchMyclass(e) {
    // 用户学号
    let useraccount = that.data.UserInfo.account
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '提示',
      content: '确定要在此和同学们告别吗？',
      success(res) {
        if (res.confirm) {
          db.collection('myclass').doc(id).update({
            data: {
              list: _.pull({
                account: _.eq(useraccount),
              })
            },
            success: async function (res) {
              // 同时将这名成员从班级社区中清除
              await db.collection('chat-msg').where({
                ChatCommunityId: 'chat' + that.data.myclass.myclassId
              }).update({
                data: {
                  members: _.pull({
                    account: _.eq(useraccount),
                  })
                },
                success: function (res) {
                  console.log(res);
                }
              })
              // 同时将这名成员从课程成员中清除
              await db.collection('course').where({
                'class.classId': that.data.myclass.myclassId
              }).update({
                data: {
                  courseMember: _.pull({
                    account: _.eq(accountkey),
                  })
                },
                success: function (res) {
                  console.log(res);
                  App.toast.showToast('退出成功，离别是下一次相逢', 'none')
                  setTimeout(() => {
                    App.route.redirTo('/pages/myclass/list/index')
                  }, 1500)
                }
              })
            }
          })
        } else if (res.cancel) {
          App.toast.showToast('吓死我啦', 'error')
        }
      }
    })
  },
  // 查看班级人群详情
  memberslist(e) {
    console.log(e.currentTarget.dataset);
    let myclassid = e.currentTarget.dataset.id
    App.route.navTo('/pages/myclass/details/member/index', myclassid)
  },

  // 跳转文件
  appFolder(e) {
    console.log(e.currentTarget.dataset);
    let path = e.currentTarget.dataset.path
    let classid = e.currentTarget.dataset.classid
    App.route.navTo(path, classid)
  },

})